package com.heima.juc.n3;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author : leimingchao
 * @date Date : 2022年02月08日 23:28
 */
@Slf4j(topic = "c.TestJoin")
public class TestJoin {

    static int r = 0;
    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) throws InterruptedException {
        // test2();
        test3();
    }

    private static void test2() throws InterruptedException {

        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                r1 = 10;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                r1 = 20;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        LocalDateTime start = LocalDateTime.now();

        t1.start();
        t2.start();

        log.debug("join begin");

        t1.join();
        log.debug("t1 join begin");

        t2.join();
        log.debug("t2 join begin");

        LocalDateTime end = LocalDateTime.now();

        long millis = Duration.between(start, end).toMillis();

        log.debug("r1:{} r2:{} cost:{}",r1, r2, millis);
    }

    private static void test3() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                r1 = 10;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        LocalDateTime start = LocalDateTime.now();

        t1.start();

        log.debug("join begin");
        t1.join(3000);

        LocalDateTime end = LocalDateTime.now();

        long millis = Duration.between(start, end).toMillis();

        log.debug("r1: {} r2:{} cost:{}",r1, r2, millis);
    }

}
